// UserGroupDAO.java
package com.bcb.dao;

import com.bcb.model.UserGroup;
import my.bcb.util.DBConnection;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserGroupDAO {
    private Connection getConnection() throws SQLException {
        return DBConnection.getConnection();
    }
    
    public List<UserGroup> findAll() {
        String sql = "SELECT * FROM user_groups ORDER BY group_id";
        List<UserGroup> groups = new ArrayList<>();
        
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            
            while (rs.next()) {
                groups.add(mapResultSetToUserGroup(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return groups;
    }
    
    public UserGroup findById(int groupId) {
        String sql = "SELECT * FROM user_groups WHERE group_id = ?";
        UserGroup group = null;
        
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, groupId);
            ResultSet rs = pstmt.executeQuery();
            
            if (rs.next()) {
                group = mapResultSetToUserGroup(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return group;
    }
    
    private UserGroup mapResultSetToUserGroup(ResultSet rs) throws SQLException {
        UserGroup group = new UserGroup();
        group.setGroupId(rs.getInt("group_id"));
        group.setGroupName(rs.getString("group_name"));
        group.setGroupDescription(rs.getString("group_description"));
        return group;
    }
}